package initialize

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	_ "github.com/mbobakov/grpc-consul-resolver"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"shop_srv_api/user_web/global"
	"shop_srv_api/user_web/proto"
)

// InitSrvConnLoadLB 有负载均衡功能
func InitSrvConnLoadLB() {
	consul := global.ServerConfig.ConsulConfig
	dial, err := grpc.Dial(fmt.Sprintf("consul://%s:%d/%s?wait=14s", consul.Host, consul.Port, global.ServerConfig.UserSrvConfig.Name), grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`"loadBalancingPolicy":"round_robin"`))
	if err != nil {
		zap.S().Fatal("【InitSrvConnLoadLB】用户服务失败", err.Error())
	}
	client := proto.NewUserClient(dial)
	global.UserSrvClient = client
}

func InitSrvConn() {
	//从注册中心拉取服务
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", global.ServerConfig.ConsulConfig.Host,
		global.ServerConfig.ConsulConfig.Port)
	newClient, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	data, err := newClient.Agent().ServicesWithFilter(fmt.Sprintf("Service == \"%s\"", global.ServerConfig.UserSrvConfig.Name))
	if err != nil {
		panic(err)
	}
	userSrvHost := ""
	userSrvPort := 0
	for _, v := range data {
		userSrvHost = v.Address
		userSrvPort = v.Port
		break
	}
	if userSrvHost == "" {
		zap.S().Fatal("[InitSrvConn] 连接 [用户服务失败]")
		return
	}

	//连接grpc server
	conn, err := grpc.NewClient(fmt.Sprintf("%s:%d", userSrvHost,
		userSrvPort), grpc.WithInsecure())
	if err != nil {
		zap.S().Errorw("GetUsrList连接用户服务失败", "msg", err.Error())
		return
	}
	//后续下线了 或者改端口了
	client := proto.NewUserClient(conn)
	//一个连接多个go协程共用 加连接池
	global.UserSrvClient = client
}
